package com.bos.controller;

import com.bos.data.model.*;
import com.bos.data.repositories.jpa.CustomerJPARepository;
import com.bos.service.LogsService;
import com.bos.service.ProjectPropertyService;
import com.bos.service.ProjectService;
import com.bos.service.Project_itemSerice;
import com.bos.common.PageData;
import com.bos.util.WeiXinParamesUtil;
import com.bos.util.HttpUtil;
import com.bos.util.SendMessage;
import com.google.common.base.Strings;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.*;

/*
 * 首页项目的显示（就是一些基本功能的完善）
 *
 * */
@Controller
public class ProjectController {
    //在需要写入日志的地方引入：
    private Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    @Qualifier("projectServiceImpl")
    ProjectService projectService;
    @Autowired
    private ProjectPropertyService projectPropertyService;

    @Autowired
    private Project_itemSerice proItemSerice;

    @Autowired
    private LogsService logsService;

    @Autowired
    private CustomerJPARepository customerJPARepository;

    // 1.查询出Project表中的数据
    @RequestMapping(value = "/showAll")
    public String findAll(HttpSession session,HttpServletRequest request) {
        int pageNo = 1;
        PageData data = projectService.findWithTerm(null, null, null, null, null, PageData.DEFAULTPAGESIZE, pageNo);

        List<BosUserModel> users = projectService.findUsers();
        List<ProjectPropertyModel> columns = projectPropertyService.getAllProperty();
        List<ProjectItemModel> proitems = proItemSerice.findAll();
        //查出字典表中的所有的项目进度,工作类别,项目组,订阅人,查询出项目表中的项目负责人
        List<BosParamModel> progress = projectService.findBos_params("项目进度");
        List<BosParamModel> pType = projectService.findBos_params("工作类别");
        List<BosParamModel> pGroups = projectService.findBos_params("项目组");
        List<BosCustomerModel> customerList=customerJPARepository.findAll();
        List<BosProjectModel> leaders=projectService.findLeaders();
        session.setAttribute("users", users);
        session.setAttribute("list", data);
        session.setAttribute("column", columns);
        session.setAttribute("proItems", proitems);
        session.setAttribute("progress", progress);
        session.setAttribute("pType", pType);
        session.setAttribute("pGroups", pGroups);
        session.setAttribute("customerList",customerList);
        session.setAttribute("leaders",leaders);
        String btnStatus=request.getParameter("btnStatus");
        if(Strings.isNullOrEmpty(btnStatus)){
            session.setAttribute("btnStatus","none");
        }else {
            session.setAttribute("btnStatus",btnStatus);
        }
        return "bosIndex";
    }

    //2.点击添加新项目的时候跳转到这个接口将数据传给前台页面
    @RequestMapping(value = "/toUser")
    public String gerUser(HttpSession session) {
        //1.接下来查询出用户表的数据，将结果保存到页面上（用来企业微信成员信息）
        List<BosUserModel> users = projectService.findUsers();
        session.setAttribute("users", users);

        //这里还要根据typeName为项目进度的数据
        List<BosParamModel> params = projectService.findBos_params("项目进度");
        session.setAttribute("params", params);
        //这里要根据typeName 为项目组来查询对应得数据
        List<BosParamModel> groups = projectService.findBos_params("项目组");
        session.setAttribute("groups", groups);
        //这里要根据typeName 为工作类别来查询对应得数据
        List<BosParamModel> types = projectService.findBos_params("工作类别");
        session.setAttribute("types", types);
        return "jsp/xinjian";
    }

    // 2.将数据插入到Project表中
    @RequestMapping(value = "/insertProject", method = RequestMethod.POST)
    public String insertAll(@ModelAttribute BosProjectModel newModel,@ModelAttribute TProjectHistoryModel newhistoryModel,
                            HttpServletRequest request, HttpSession session)
            throws Exception {
        newModel.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        newhistoryModel.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        String[] newColumn = request.getParameterValues("newColumn");
        String proitid = request.getParameter("proitid");

        //插入项目表
        int newId = projectService.addProject(newModel);
        //插入到项目历史表
        int newHistoryId=projectService.addProjectHistory(newhistoryModel);

        //插入project_item表
        if(!Strings.isNullOrEmpty(proitid)){
            for (int i = 0; i < newColumn.length; i++) {
                ProjectItemModel pitemModel = new ProjectItemModel();
                pitemModel.setProid(newId);
                pitemModel.setProitid(Integer.valueOf(proitid));
                pitemModel.setValue(newColumn[i]);
                proItemSerice.addProItem(pitemModel);
                //复制一份到历史表中
                ProjectItemHistoryModel historyItem=new ProjectItemHistoryModel();
                historyItem.setProid(newId);
                historyItem.setProitid(Integer.valueOf(proitid));
                historyItem.setValue(newColumn[i]);
                historyItem.setHistoryPid(newHistoryId);
                proItemSerice.addProItemHistory(historyItem);
            }
        }
        //插入日志
        logsService.insertLogs(session, "新增项目:["+newModel.getwName()+"]");
        return "redirect:showAll";
    }

    // 4.根据id修改数据
    @RequestMapping(value = "/updateProjectById", method = RequestMethod.POST)
    public String updateById(@ModelAttribute BosProjectModel newModel,@ModelAttribute TProjectHistoryModel newhistoryModel, HttpServletRequest request, HttpSession session,
                             @RequestParam("message") String message) throws Exception {
        String[] oldothersColumn = request.getParameterValues("oldothersColumn");
        String[] othersCol = request.getParameterValues("othersColumn");
        String[] idarr = request.getParameterValues("pitemid");
        String[] proitids = request.getParameterValues("proitid");

        BosProjectModel oldModel = projectService.findProjectById(newModel.getId());
        //表示没有做任何修改 oldothersColumn==othersCol
        if (oldModel.equals(newModel) && Arrays.equals(oldothersColumn, othersCol)) {
            return "redirect:showAll";
        }
        newModel.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        newhistoryModel.setId(null);
        newhistoryModel.setUpdateTime(new Timestamp(System.currentTimeMillis()));


        //更新项目表
        projectService.updProject(newModel);
        int newHistoryId = projectService.addProjectHistory(newhistoryModel);

        //更新project_item表
        if (idarr != null) {
            for (int i = 0; i < idarr.length; i++) {
                proItemSerice.updProItem(Integer.valueOf(idarr[i]), othersCol[i]);
            }
        }

        //新增project_item_histroy表
        List<ProjectItemHistoryModel> historyItemList = new ArrayList<>();
        if (proitids != null && !proitids[0].trim().isEmpty()) {
            for (int i = 0; i < proitids.length; i++) {
                ProjectItemHistoryModel newItemModel = new ProjectItemHistoryModel();
                newItemModel.setProid(newModel.getId());
                newItemModel.setProitid(Integer.valueOf(proitids[i]));
                newItemModel.setValue(othersCol[i]);
                newItemModel.setHistoryPid(newHistoryId);
                historyItemList.add(newItemModel);
            }
            proItemSerice.insertItemHistory(historyItemList);
        }

        //由进行中-正常更改为进行中-紧急
        String[] strs = message.split("更改为");
        String before = strs[0].toString();
        String after = strs[1].toString();
        if (newModel.getOthers1() != null) {
            String[] subscribers = newModel.getOthers1().split(",");
            if (!after.equals(before) && subscribers != null) {
                //根据cname去查询出bos_customer中的数据
                for (int i = 0; i < subscribers.length; i++) {
                    BosCustomerModel customer = projectService.findCustomerByCname(subscribers[i]);
                    //接下来给这个客户发送模板消息
                    //先给模板中设置参数
                    Template tem = new Template();
                    tem.setTemplateId(WeiXinParamesUtil.TEMPLATEID);  //模板id
                    tem.setTopColor("#00DD00");
                    tem.setToUser(customer.getOpenId());//得到用户的openid
                    tem.setUrl("");
                    List<TemplateParam> paras = new ArrayList<TemplateParam>();
                    paras.add(new TemplateParam("first", "我们将给您推送一些关于您项目进度的消息:", "#FF3333"));
                    paras.add(new TemplateParam("keyword1", newModel.getwName(), "#0044BB"));//项目名称
                    paras.add(new TemplateParam("keyword2", newModel.getLeader(), "#0044BB"));//负责人
                    //paras.add(new TemplateParam("keyword3", newModel.getsTime(), "#0044BB"));//开始时间
                    paras.add(new TemplateParam("keyword3", message, "#0044BB"));//项目进度
                    paras.add(new TemplateParam("remark", "感谢您对我们的支持!", "#AAAAAA"));
                    tem.setTemplateParamList(paras);
                    //将Accesstoken拿到
                    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
                    String APPID = WeiXinParamesUtil.APPID;
                    String SECRET = WeiXinParamesUtil.SECRET;
                    url = url.replace("APPID", APPID);
                    url = url.replace("APPSECRET", SECRET);
                    String content = HttpUtil.httpUrlConnect(url, null, "GET");
                    Map<String, Object> map = HttpUtil.getAccessTokenByJsonStr(content);
                    String accessToken = (String) map.get("access_token");
                    boolean result = SendMessage.sendTemplateMsg(accessToken, tem);
                }
            }
        }
        //插入日志(此中括号不能轻易删除,toProjectHistory接口有用到)
        logsService.insertLogs(session, "更新项目 [" + newModel.getwName() + "]");
        return "redirect:showAll";
    }


    // 6根据id查询出对应的数据
    @RequestMapping(value = "/findProjectById")
    public String findById(Model model, @RequestParam("id") int id,HttpSession session) {
        BosProjectModel pro = projectService.findProjectById(id);
        model.addAttribute("pro", pro);
        List<ProjectItemModel> proitem = proItemSerice.findByProid(id);
        model.addAttribute("proItems", proitem);

        //查出字典表中的所有的项目进度,工作类别,项目组,订阅人,项目负责人
        List<BosParamModel> progress = projectService.findBos_params("项目进度");
        List<BosParamModel> pType = projectService.findBos_params("工作类别");
        List<BosParamModel> pGroups = projectService.findBos_params("项目组");
        List<BosCustomerModel> customerList=customerJPARepository.findAll();
        List<BosUserModel> users = projectService.findUsers();
        session.setAttribute("users", users);
        session.setAttribute("progress", progress);
        session.setAttribute("pType", pType);
        session.setAttribute("pGroups", pGroups);
        session.setAttribute("customerList",customerList);
        return "jsp/update";
    }


    // 跟添加字段的方法一起用
    @RequestMapping("/show")
    public String add(@ModelAttribute(value = "content") String prama1,
                      Model model, HttpSession session) {
        List<BosProjectModel> projects = projectService.findProject();
        model.addAttribute("projects", projects);
        // 将字段的描述内容保存到session中
        session.setAttribute("content", prama1);
        return "bosIndex";
    }

    //10.根据序号，工作类型，项目名称，开始时间，完成时间，项目进度，项目情况，负责人进行查询出结果
    @RequestMapping(value = "/selectByWhere", method = RequestMethod.POST)
    public String selectByAll(@RequestParam("condition") String where,
                              HttpServletRequest request, HttpServletResponse response, Model model,HttpSession session) throws Exception {
        //获取页面的当前页数和页面大小,默认是第一页
        String pageIndex = request.getParameter("pageNo");
        String setPageSize = request.getParameter("setPageSize");
        int pageNo = 1, pageSize = PageData.DEFAULTPAGESIZE;
        if (!Strings.isNullOrEmpty(pageIndex)) {
            pageNo = Integer.valueOf(pageIndex);
        }
        if (!Strings.isNullOrEmpty(setPageSize)) {
            pageSize = Integer.valueOf(setPageSize);
        }
        String[] shuigou = request.getParameterValues("start");
        String[] wtype = request.getParameterValues("wtype");
        String[] pteam = request.getParameterValues("pteam");
        String[] pleader = request.getParameterValues("pleader");
        List<String> sList = shuigou != null ? Arrays.asList(shuigou) : new ArrayList<>();
        List<String> wList = wtype != null ? Arrays.asList(wtype) : new ArrayList<>();
        List<String> pList = pteam != null ? Arrays.asList(pteam) : new ArrayList<>();
        List<String> pleaderList = !pleader[0].equals("") ? Arrays.asList(pleader) : new ArrayList<>();
        //将前台的搜索条件再返回给前台显示
        String start = "", wType = "", pTeam = "", pLeader = "";
        if (shuigou != null) {
            for (int i = 0; i < shuigou.length; i++) {
                start += shuigou[i];
            }
        }
        if (wtype != null) {
            for (int i = 0; i < wtype.length; i++) {
                wType += wtype[i];
            }
        }
        if (pteam != null) {
            for (int i = 0; i < pteam.length; i++) {
                pTeam += pteam[i];
            }
        }
        if (pleader != null) {
            for (int i = 0; i < pleader.length; i++) {
                pLeader += pleader[i];
            }
        }
        //1.第一种情况
        PageData data = projectService.findWithTerm(where, sList, wList, pList, pleaderList, pageSize, pageNo);

        model.addAttribute("list", data);
        model.addAttribute("condition", where);
        model.addAttribute("start", start);
        model.addAttribute("wtype", wType);
        model.addAttribute("pteam", pTeam);
        model.addAttribute("pleader", pLeader);
        String btnStatus=request.getParameter("btnStatus");
        if(Strings.isNullOrEmpty(btnStatus)){
            session.setAttribute("btnStatus","none");
        }else {
            session.setAttribute("btnStatus",btnStatus);
        }
        //接下来将得到的值传给页面
        return "bosIndex";
    }

    //后台对导出Excel开设的方法
    @RequestMapping(value = "/selectByWhere2/{type}")
    public String selectByAll2(@RequestParam("condition") String where,
                               HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("type") int type) {
        String pageIndex = request.getParameter("pageNo");
        int pageNo = 1;
        if (pageIndex != null) {
            pageNo = Integer.valueOf(pageIndex);
        }
        String[] shuigou = request.getParameterValues("start");
        String[] wtype = request.getParameterValues("wtype");
        String[] pteam = request.getParameterValues("pteam");
        String[] pleader = request.getParameterValues("pleader");

        List<String> sList = shuigou != null ? Arrays.asList(shuigou) : new ArrayList<>();
        List<String> wList = wtype != null ? Arrays.asList(wtype) : new ArrayList<>();
        List<String> pList = pteam != null ? Arrays.asList(pteam) : new ArrayList<>();
        List<String> pleaderList = !pleader[0].equals("") ? Arrays.asList(pleader) : new ArrayList<>();

        //导出所有项目到excel
        if (type == 2) {
            PageData data = projectService.findWithTerm(where, sList, wList, pList, pleaderList, 0, 0);
            model.addAttribute("projects2", data);
        } else {
            PageData data = projectService.findWithTerm(where, sList, wList, pList, pleaderList, PageData.DEFAULTPAGESIZE, pageNo);
            model.addAttribute("projects2", data);
        }

//        System.out.println(where);
//        //导出Excel分为四种情况
//        //1.当输入框和复选框俩着都没选中的时候,那么导出的Excel是全部数据
//        if (null == where || "".equals(where)) {
//            if (null == shuigou || 0 == shuigou.length) {
//                List<projectModel> pros = projectService.findProject();
//                System.out.println("输入框和复选框都没选中");
//                model.addAttribute("projects2", pros);
//            } else {
//                //1.当地址栏上显示showAll 的时候，那么直接点击搜索，点击导出excel的时候查询出全部数据
//                //2.地址栏为showAll,勾选复选框，不点击搜索的话直接点击导出Excel的话，数据是正确的，
//                //3.当地址栏上显示selectByWhere 的时候，将复选框勾选上，不用点击搜索，点击导出excel,数据正确
//                List<projectModel> pros1 = projectService.selectByWhere("", shuigou, wtype, pteam, pleader);
//                System.out.println("输入框没选中，但是复选框选中了的时候");
//                model.addAttribute("projects2", pros1);
//            }
//        } else {
//            //这个的话，导出的也是全部数据(打印出的where是null的)原因再于点击搜索，文本框中的值会清空
//            if (null == shuigou || 0 == shuigou.length) {
//                List<projectModel> pros2 = projectService.selectByWhere(where, null, wtype, pteam, pleader);
//                System.out.println("输入框选中，复选框没选中");
//                model.addAttribute("projects2", pros2);
//            } else {
//                //这个导出的也是全部数据
//                List<projectModel> pros2 = projectService.selectByWhere(where, shuigou, wtype, pteam, pleader);
//                System.out.println("输入框和复选框选中了的时候");
//                model.addAttribute("projects2", pros2);
//            }
//        }
        //进行导入Excel表单的操作
        return "jsp/test";

    }

    //11。根据id删除数据
    @RequestMapping(value = "/deleteByid/{id}")
    public ModelAndView deleteByID(@PathVariable("id") int id, Model model, ModelAndView mv, HttpSession session) {
        //在这边的话调用dao层删除操作的语句
        int row = projectService.deleteById(id);
        if (row > 0) {

            System.out.println("删除成功");
        }
        //插入日志
        logsService.insertLogs(session, "删除项目");
        mv.setViewName("redirect:../showAll");
        return mv;
    }

    //12.获取前台页面传过来的json数据，用来修改负责人
    @RequestMapping(value = "/getJson", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    List<String> getJson(@RequestBody BosProjectModel project) {
        List<String> list = new ArrayList<String>();
        System.out.println("111111" + project.getLeader());
        BosProjectModel pro = new BosProjectModel();
        pro.setLeader(project.getLeader());
        pro.setId(project.getId());
        int row = projectService.updateLeader(pro);
        if (row > 0) {
            System.out.println("修改成功");

        }
        list.add(project.getLeader());
        return list;
    }

    //跳转到项目历史页面中
    @RequestMapping(value = "toProjectHistory/{id}")
    public String toProjectHisttory(@PathVariable("id") int id,Model model){
        //拿到操作日志里的项目名称
        LogsModel m=projectService.findLogById(id);
        if(m!=null){
            String pname=m.getMessage();
            //截取出项目名称
            String newName=pname.substring(pname.indexOf("[")+1,pname.indexOf("]"));
            //从项目历史表中根据项目名称查出数据
            List<TProjectHistoryModel> models=projectService.getAllProjectHistoryByWName(newName);
            model.addAttribute("list",models);
            //查出项目id，再查出id关联的新字段
//            int pid=projectService.findByName(newName).getId();
//            List<ProjectItemHistoryModel> proitems = proItemSerice.findByPid(pid);
//            List<ProjectPropertyModel> columns = projectPropertyService.getAllProperty();
//            model.addAttribute("items",proitems);
//            model.addAttribute("columns",columns);
            logger.info("is end");
        }
        return "project/projectHistory";
    }

    @RequestMapping(value = "copyProject/{id}")
    public String copyProject(@PathVariable("id") int id,HttpSession session){
        String pname=projectService.copyProject(id);
        //动态字段以后处理
        //.........
        //插入日志
        logsService.insertLogs(session, "复制一条项目:["+pname+"]");
        return "redirect:../showAll";
    }
}